package com.baizhi.controller;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baizhi.entity.PmsBrand;
import com.baizhi.service.IPmsBrandService;
import com.baizhi.vo.R;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lby
 * @since 2020-09-24
 */
@RestController
@RequestMapping("brand")
public class PmsBrandController  {
    @Autowired
    private IPmsBrandService iPmsBrandService;

   /* @GetMapping("selectBrandBySize")
    public Map<String, Object> selectBrandBySize(Integer page, Integer limit){
        Map map = iPmsBrandService.selectBrandBySize(page, limit);
        System.out.println("map = " + map);
        return map;
    }*/

    @GetMapping("selectBrandBySize")
    public R selectBrandBySize(Integer page, Integer limit){
        return iPmsBrandService.selectBrandBySizeR(page,limit);
    }

    @RequestMapping("importBrand")
    public void importBrand(MultipartFile file)throws Exception{
        InputStream inputStream = file.getInputStream();
        //HSSFWorkbook sheets = new HSSFWorkbook(inputStream);
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<PmsBrand> pmsBrands = ExcelImportUtil.importExcel(inputStream, PmsBrand.class, importParams);

        for (PmsBrand brand : pmsBrands) {
            iPmsBrandService.addPmsBrand(brand);
        }
    }

@RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletResponse response) throws IOException {
//        生成 Excel 文件对象
    Workbook workbook = iPmsBrandService.downloadExcel();
    String fileName= UUID.randomUUID().toString().substring(0, 4) + "brand.xls";
//        下载
    response.setHeader("Content-Disposition",
            "attachment;fileName="
                    + URLEncoder.encode(fileName,"utf-8"));
//    设置下载格式
    response.setContentType("application/vnd.ms-excel");

    workbook.write(response.getOutputStream());

    }
}
